import os
from tornado.web import RequestHandler

from Server.Utils import network, fileType, media
from Server import const, var


def reloadHtmlFile(obj: RequestHandler, on: bool = True):
    if not on:
        return
    for loader in obj._template_loaders.values():
        loader.reset()


def makeDirHtml(obj: RequestHandler, dirPath: str, hiddenConfig: dict, route='', proxyUrl='/', routeFrom='/'):
    if dirPath[-1] == '/':
        dirPath = dirPath[:-1]
    title = dirPath.split('/')[-1]
    if proxyUrl != '' and proxyUrl[-1] == '/':
        proxyUrl = proxyUrl[:-1]
    dirPath += '/'
    indexHtml = dirPath + const.DirIndexFile
    if os.path.exists(indexHtml) and os.path.isfile(indexHtml):
        return media.readFile(indexHtml)
    fileList = {
        'dir': [],
        'image': [],
        'audio': [],
        'other': []
    }
    for path, dirs, files in os.walk(dirPath):
        if path != dirPath:
            break
        for subdir in dirs:
            if fileType.isHiddenPath(dirPath + subdir, hiddenConfig):
                continue
            fileList['dir'].append({
                # 'u': network.quoteUrlCode('{0}/{1}'.format(proxyUrl + route, subdir)),
                'u': network.quoteUrlCode('./{0}/'.format(subdir)),
                'n': './{0}/'.format(subdir)
            })
        for file in files:
            if fileType.isHiddenPath(dirPath + file, hiddenConfig):
                continue
            item = {
                # 'u': network.quoteUrlCode('{0}/{1}'.format(proxyUrl + route, file)),
                'u': network.quoteUrlCode('./{0}'.format(file)),
                'n': file
            }
            fType = fileType.getFileType(file)
            if fType == fileType.Type.IMAGE:  # 图片类型
                fileList['image'].append(item)

            elif fType == fileType.Type.AUDIO:  # 音频类型
                fileList['audio'].append(item)

            else:  # 其他类型
                fileList['other'].append(item)

    hf = var.translate(const.HtmlDirFilePath)
    reloadHtmlFile(obj, True)
    return obj.render_string(hf, proxy_url=proxyUrl, title=title, version=const.VERSION, dirs=fileList['dir'],
                             others=fileList['other'], audios=fileList['audio'], images=fileList['image'],
                             __path=route, __route_from=routeFrom)


def makeRootHtml(obj: RequestHandler, routePath: dict, proxyUrl: str = '/'):
    if proxyUrl != '' and proxyUrl[-1] == '/':
        proxyUrl = proxyUrl[:-1]
    defRoutes = ['/', const.IconRoute, const.JsRoute, const.CssRoute]
    routes = []
    for key in routePath.keys():
        if key in defRoutes:
            continue
        routes.append({
            # 'u': network.quoteUrlCode(proxyUrl + key),
            'u': network.quoteUrlCode('.{0}/'.format(key)),
            'n': '.{0}/'.format(key)
        })
    hf = var.translate(const.HtmlRootFilePath)
    reloadHtmlFile(obj, True)
    return obj.render_string(hf, proxy_url=proxyUrl, title='root', version=const.VERSION, routes=routes)


def makeAudioHtml(obj: RequestHandler, route='', proxyUrl='/', routeFrom='/'):
    if proxyUrl != '' and proxyUrl[-1] == '/':
        proxyUrl = proxyUrl[:-1]
    aTitle = (proxyUrl + route).split('/')[-1]
    audio = {
        # 'u': network.quoteUrlCode(proxyUrl + route),
        'u': network.quoteUrlCode('./{0}'.format(aTitle)),
        't': fileType.getContentType(aTitle)
    }
    hf = var.translate(const.HtmlAudioFilePath)
    reloadHtmlFile(obj, True)
    return obj.render_string(hf, proxy_url=proxyUrl, title=aTitle, version=const.VERSION, audio=audio)
